<template>
  <div class="loginPage">
    <!-- pi浏览器登录 -->
    <div class="piLoginPage" v-if="piLoginPageShow">
      <div class="paypishopdiv">
        <img src="/images/Home/pipayshop_home.png" alt="" class="pipayshop_home" />
      </div>

      <div id="go_pi">
        <img src="/images/Home/small_pi_1.png" alt="" class="small_pi" />
      </div>
    </div>

    <!-- 外部浏览器登录 -->
    <div class="external_browser" v-if="externalBrowserShow">
      <div class="logo">
        <img src="/images/Home/pipayshop_home.png" alt="" class="logo1" />
        <img src="/images/Home/small_pi_1.png" alt="" class="logo2" />
      </div>

      <div class="form">
        <div class="title">Login</div>

        <input type="text" name="" id="" v-model="formData.piName" placeholder="PiUserName" />

        <input type="text" name="" id="" v-model="formData.password" placeholder="Password" />

        <div class="code">
          <input type="text" name="" id="" v-model="formData.checkCode" placeholder="Code" />

          <img src="" id="codeImg" alt="code" />
        </div>

        <div class="submit" @click="userRegisterFun">Sign in</div>
      </div>
    </div>
  </div>
</template>

<script>
import { ToastFun } from "@/hook/toast";

import { useUseStore } from "@/stores/user";
import { userStore } from "@/stores/userStore.js";
import { useIndexStore } from "@/stores/indexStore";

import {
  insertRegisterData,
  userRegister,
  checkCode,
} from "@/server/api/userInfo";
import { Login } from "@/server/api/LoginApi.js";
import { incomplete } from "@/server/api/rechargeOrder";

export default {
  data() {
    let piLoginPageShow = false; // 控制pi浏览器登录页面显示隐藏
    let externalBrowserShow = false; // 控制外部浏览器登录页面显示隐藏

    // 判断当前浏览器
    const userAgent = window.navigator.userAgent;

    let sessionId = null;

    // //外部登录q请求体
    let formData = {
      piName: "test888",
      password: "123456",
      checkCode: "",
    };
    // let formData = {
    //   piName: "",
    //   password: "",
    //   checkCode: "",
    // };

    return {
      formData,
      userAgent,
      sessionId,

      piLoginPageShow,
      externalBrowserShow,
    };
  },

  methods: {
    // 登录方法
    LoginFun() {

      // 初始化pi sandbox设置沙盒环境
      Pi.init({ version: "2.0", sandbox: false });
      console.log("pi登录的方法");
      let _this = this; // 获取this，用于深层调用
      let msg = ""; // 轻提示的消息

      const scopes = ["payments", "username", "wallet_address"];

      const onIncompletePaymentFound = (payment) => {
        return incomplete({
          identifier: payment.identifier,
          transaction: {
            _link: payment.transaction._link,
            txid: payment.transaction.txid,
          },
        }).then((data) => {
          console.log(data);
        });
      };

      // pi获取用户信息接口
      Pi.authenticate(scopes, onIncompletePaymentFound)
        .then((auth) => {
          console.log("auth", auth);

          // 用于传到后端的登录信息
          let userInfo = {
            accessToken: auth.accessToken,
            userId: auth.user.username,
            userName: auth.user.username,
          };

          // 存入userId
          useUseStore().userId = auth.user.username;
          // console.log(userInfo);

          // 后端的登录接口
          Login(userInfo).then(({ data }) => {
            ToastFun("show", { msg: "Login", position: "bottom" }); // 轻提示
            console.log("登录信息", data);

            if (data.data.code == 200) {
              // 将用户信息存入pinia
              // data.data.data.user.userImage = useUseStore().ing + userImage
              useUseStore().userInfo = data.data.data.user;
              useUseStore().token = data.data.data.token;
              _this.$router.push("/");
              msg = "Login succeeded";
              // _this.startSpecialAnimation();

              // 发布消息到socket Login() 存入userId
              _this.$socket.emit("login", auth.user.username);
            } else {
              msg = "Login failed";
            }

            ToastFun("show", { msg, position: "bottom" }); // 轻提示
          });
        })
        .catch(() => {
          msg = "Login failed";
          ToastFun("show", { msg, position: "bottom" }); // 轻提示
        });
    },

    // 动画跳转到首页
    // startSpecialAnimation() {
    //   let _this = this;

    //   const box = document.getElementById("go_pi");

    //   const boxRect = box.getBoundingClientRect();
    //   const boxLeftPosition = boxRect.left;

    //   // 盒子还未移动到最左侧，继续监听
    //   if (boxLeftPosition > 1) {
    //     requestAnimationFrame(() => {
    //       _this.startSpecialAnimation(box);
    //     });
    //   }
    //   // 盒子移动到最左侧，执行下一个动画
    //   else {
    //     box.style.animation =
    //       "specialAnimation 2s forwards,rotate 1s infinite alternate";

    //     setTimeout(() => {
    //       box.style.animation = "specialAnimation 1s forwards"; // 停止waveJump动画

    //       setTimeout(() => {
    //         _this.$router.push("/");
    //       }, 100);
    //     }, 1000);
    //   }
    // },

    // 外部登录接口
    userRegisterFun() {
      ToastFun("Loading", { duration: 3000 }); // 加载提示

      userRegister(this.formData, this.sessionId).then(({ data }) => {
        if (data.code == 200) {
          ToastFun("show", { msg: "success" });

          // 将用户信息存入pinia
          useUseStore().userId = data.data.data.user.uid;
          useUseStore().userInfo = data.data.data.user;
          useUseStore().token = data.data.data.token;

          useIndexStore().isRequird = true;
          console.log("用户信息", useUseStore());

          this.$router.push("/"); // 跳转首页
        } else {
          ToastFun("fail", {});
          location.reload();
        }
      });
    },
  },

  beforeCreate() {
    userStore().userInfo = {};
  },

  created() {
    // // pi浏览器登录
    // this.LoginFun(); // pi登录方法
    if (window.navigator.userAgent.includes("PiBrowser")) {
      this.LoginFun(); // pi登录方法
      console.log("Pi登录方法下面的文字提示");
      this.piLoginPageShow = true; // 显示pi登录页面
    }
    // 外部浏览器登录
    else {
      this.externalBrowserShow = true; // 显示外部登录页面
    }
  },

  mounted() {
    if (!window.navigator.userAgent.includes("PiBrowser")) {
      checkCode().then((data) => {
        let codeImg = document.getElementById("codeImg"); // 获取验证码
        let imageType = data.headers["content-type"]; //获取图片类型
        const blob = new Blob([data.data], { type: imageType }); // 生成blob
        const imageUrl = (window.URL || window.webkitURL).createObjectURL(blob); // 生成路径
        codeImg.src = imageUrl; // 赋值
        this.sessionId = data.headers.sessionid; // 获取sessionId
        // console.log("sessionId", this.sessionId);
      });
    }
  },

  sockets: {
    loginInfo(data) {
      console.log(data);
    },
  },
};
</script>

<style lang="scss">
.loginPage {
  min-height: 100vh;
  max-height: 100vh;
  overflow: hidden;

  >.piLoginPage {
    .formList {
      padding: 15rem;

      .tips {
        padding-left: 5rem;
        margin-bottom: 15rem;
        font-size: 20rem;
        font-weight: 500;
      }

      input {
        width: 100%;
        padding: 5rem 0;
        margin-bottom: 10rem;
        border-bottom: 1rem solid #ccc;

        font-size: 14rem;

        text-indent: 0.5em;
      }

      .submit {
        width: 50rem;
        padding: 5rem 10rem;

        color: #fff;
        font-size: 14rem;
        line-height: 14rem;
        text-align: center;

        border-radius: 4rem;
        background: #662d91;
      }
    }

    .paypishopdiv {
      width: 280rem;
      position: relative;
      top: 100%;
      left: 50%;
      transform: translate(-50%, 200%);
      /*border: 1rem solid #000;*/
      z-index: -10;
    }

    .pipayshop_home {
      width: 280rem;
    }

    #go_pi {
      position: relative;
      animation: moveBox 2s infinite alternate, fastBlinking 2s infinite,
        rotate 2s infinite;
      z-index: -10;
    }

    .small_pi,
    #go_pi {
      width: 50rem;
      height: 50rem;
    }
  }

  >.external_browser {
    min-height: 100vh;
    max-height: 100vh;
    overflow: hidden;

    // background-image: linear-gradient(
    //   to bottom,
    //   #fff 0%,
    //   #a375c7 20%,
    //   #714592 50%,
    //   #803cb4 100%
    // );

    >.logo {
      display: flex;
      justify-content: center;
      flex-wrap: wrap;

      padding-top: 50rem;

      position: relative;

      >.logo1 {
        width: 80%;
      }

      >.logo2 {
        position: absolute;
        top: 110rem;
        right: 100rem;

        width: 60rem;
      }
    }

    >.form {
      position: relative;
      z-index: 10;

      margin: 80rem 20rem 0;
      padding: 20rem;

      border-radius: 20rem;
      box-shadow: 3rem 3rem 20rem -3rem rgba(105, 105, 105, 0.678);

      display: flex;
      flex-wrap: wrap;

      >.title {
        font-size: 26rem;
        font-weight: 800;
        color: #444;

        margin-bottom: 10rem;
      }

      >.code {
        width: 100%;
        display: flex;

        padding-bottom: 15rem;

        >input {
          margin: 0;
          margin-right: 20rem;
        }

        >img {
          width: 100rem;
        }
      }

      input {
        width: 100%;
        border-bottom: 1rem solid #888;
        padding: 10rem 0;

        font-size: 14rem;
        line-height: 14rem;

        margin-bottom: 15rem;

        text-indent: 0.5em;

        &::placeholder {
          color: #888;
        }
      }

      >.submit {
        padding: 10rem 15rem;
        margin: 20rem auto 0;

        font-size: 14rem;
        color: #fff;

        border-radius: 5rem;
        background: #662d91;
      }
    }
  }
}

@keyframes moveBox {
  0% {
    left: calc(0%);
    top: 400rem;
  }

  100% {
    left: calc(100% - 60rem);
    top: 400rem;
  }
}

@keyframes specialAnimation {
  0% {
    left: calc(0%);
    top: 400rem;
  }

  25% {
    left: 100rem;
    top: 200rem;
  }

  50% {
    left: 200rem;
    top: 300rem;
  }

  100% {
    left: 240rem;
    top: 210rem;
  }
}

@keyframes waveJump {
  0% {
    transform: translateY(0);
  }

  50% {
    transform: translateY(1000rem);
  }

  100% {
    transform: translateY(0);
  }
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

@keyframes fastBlinking {
  0% {
    opacity: 1;
  }

  25% {
    opacity: 0;
  }

  50% {
    opacity: 1;
  }

  75% {
    opacity: 0;
  }

  100% {
    opacity: 1;
  }
}
</style>
